﻿using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, ApiPaging<MenuDTO>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;

        public GetMenuHandler(IBaseRepository<MenuModel> menuRepo)
        {
            this.menuRepo = menuRepo;
        }
        public Task<ApiPaging<MenuDTO>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<MenuDTO> res = new ApiPaging<MenuDTO>();
            var menu = menuRepo.GetAll().Where(x => x.IsDelete == false);
            var model = menuRepo.GetAll().Where(x => x.IsDelete == false);
            var linq = from a in menu
                       join b in model.DefaultIfEmpty() on a.Pid equals b.Id into abGroup
                       from b in abGroup.DefaultIfEmpty()
                       select new MenuDTO
                       {
                           Id=a.Id,
                           MenuName = a.MenuName,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           Pid = a.Pid,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           Url = a.Url,
                           ParentName=b.MenuName,
                       };
            res.TotalCount = linq.Count();
            res.TotalPage = (int)Math.Ceiling((res.TotalCount * 1.0) / request.PageSize);
            res.Datas = linq.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            res.Code = ApiEnum.Success;
            res.Msg = "查询菜单信息成功";
            return Task.FromResult(res);
        }
    }
}
